﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using RoketSolutions.SP2010.Infrostructure.Localization;
using RoketSolutions.SP2010.Infrostructure.UI.Controls.Interfaces;
using RoketSolutions.SP2010.Infrostructure.UI.WebParts;
using RoketSolutions.SP2010.LinkedInWebPart.Authorization;
using RoketSolutions.SP2010.LinkedInWebPart.Common;
using RoketSolutions.SP2010.LinkedInWebPart.WebParts.ToolParts;
using RoketSolutions.SP2010.Infrostructure.Common.Extensions;
using System.Web.UI.WebControls;

namespace RoketSolutions.SP2010.LinkedInWebPart.WebParts.LinkedInWebPart
{
    [ToolboxItemAttribute(false)]
    public class LinkedInWebPart : LocalizableWebPart
    {
        const string ControlUrl = @"~/_controltemplates/RoketSolutions.SP2010.LinkedInWebPart/LinkedInAuthorizerUserControl.ascx";
        protected Control TargetControl { get; set; }

        [WebBrowsable(false)]
        [Personalizable(PersonalizationScope.User)]
        public string AccessToken { get; set; }

        [WebBrowsable(false)]
        [Personalizable(PersonalizationScope.User)]
        public string RequestToken { get; set; }

        private LinkedInWebPartSettings _settings;
        [WebBrowsable(false)]
        [Personalizable(PersonalizationScope.Shared)]
        public LinkedInWebPartSettings LinkedInWebPartSettings
        {
            get { return _settings ?? (_settings = new LinkedInWebPartSettings()); }
            set
            {
                _settings = value;
            }
        }

        protected override string ResourcesFolderPath
        {
            get
            {
                // return path of the folder where all localization resources are located
                return ResourcesLocation.GetFolderPath();
            }
        }

        protected override void OnInit(EventArgs e)
        {
            EnsureChildControls();
            base.OnInit(e);
        }

        protected override void CreateChildControls()
        {
           
            if (TargetControl == null && CheckSettings())
            {
                // try to load control
                TargetControl = Page.LoadControl(ControlUrl);
                if (TargetControl != null)
                {
                    // check whether the control supports localization
                    if (TargetControl is ILocalizableControl)
                    {
                        // set localization settings
                        ((ILocalizableControl)TargetControl).SetupConfig(ResourceConfig);
                    }

                    var linkedInControl = TargetControl as ILinkedInControl;

                    if (linkedInControl != null)
                    {
                        // apply settings
                        linkedInControl.TokenSource = new WebPartTokenSource(LinkedInWebPartSettings.ApplicationKey,
                                                                             LinkedInWebPartSettings.ApplicationSecret) { LinkedInWebPart = this };
                    }

                    Controls.Add(TargetControl);
                }
                base.CreateChildControls();
            }
        }

        private bool CheckSettings()
        {
            var isEmptyKeys =
                LinkedInWebPartSettings.ApplicationKey.IsNullOrEmpty() &&
                  LinkedInWebPartSettings.ApplicationSecret.IsNullOrEmpty();

            if (isEmptyKeys)
            {
                Controls.Add(new Label { Text = Resources.For<Labels>(ResourceConfig).Get(item => item.AppKeyNotFoundMessage) });
            }
            return !isEmptyKeys;
        }

        public override ToolPart[] GetToolParts()
        {
            var tools = new List<ToolPart> { new LinkedInToolPart(LinkedInWebPartSettings) };

            // retrieve standard tool parts
            tools.AddRange(base.GetToolParts());

            return tools.ToArray();
        }

        public void ApplySettings(LinkedInWebPartSettings settings)
        {
            LinkedInWebPartSettings = settings;
        }

        public void SaveTokens()
        {
            SetPersonalizationDirty();
            SaveProperties = true;
        }
    }
}
